package com.wwy.monitor.config;

import com.autonavi.acis.service.MailService;
import com.autonavi.acis.service.impl.MailServiceImpl;
import com.autonavi.acis.system.mail.LocalFileMailTemplateDao;
import com.autonavi.acis.system.mail.MailTemplateDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * JavaMailSender读取配置并注入到spring的ioc容器中
 */
@Configuration
public class MailingConfiguration {
    @ConfigurationProperties(prefix = "mail")
    @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setProtocol("smtp");
        javaMailSender.setJavaMailProperties(getMailProperties());
        return javaMailSender;
    }

    @Bean
    public MailService createMailService(@Value("${mail.from}") String from) {
        MailServiceImpl mailService = new MailServiceImpl();
        mailService.setFrom(from);
        return mailService;
    }

    private Properties getMailProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.debug", "false");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        return properties;
    }

    @Bean
    public MailTemplateDao createMailTemplateDao(@Value("${mail.template.path}") String basePath) {
        return new LocalFileMailTemplateDao(basePath);
    }
}
